﻿using Albatross.SampleApp.Model;
using Albatross.WPF.Common;
using Albatross.WPF.Common.ViewModels;
using Albatross.WPF.Common.Views;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace Albatross.SampleClient.ViewModels {
	[DataContract]
	public class ContactsViewModel : WorkspaceViewModel {
		public ContactsViewModel() {
			Title = "Contacts";
			Contacts = new ObservableCollection<Contact>();
		}
		public ObservableCollection<Contact> Contacts { get; private set; }

		public override async void LoadAsync(WPF.Common.IViewService viewService) {
			try {
				Contacts.Clear();
				Func<IEnumerable<Contact>> func = new Func<IEnumerable<Contact>>(ContactsService.Instance.ListContacts);
				IEnumerable<Contact> list = await Task.Run<IEnumerable<Contact>>(func);
				foreach (var item in list) {
					Contacts.Add(item);
				}
			} catch (Exception err) {
				if (viewService != null) {
					viewService.ShowErrorMessageBox(err.Message);
				}
			}
		}
		public RelayCommand<CommandParameter> SelectedContactChangedCommand { get { return new RelayCommand<CommandParameter>(SelectedContactChanged); } }
		void SelectedContactChanged(CommandParameter param) {
			if (param != null && param.Value is Contact) { 
				Contact c = (Contact)param.Value;
				param.ViewService.ShowWorkspace<ContactViewModel>(c.ID, c.ID);
				_svcs = param.ViewService;
			}
		}
		IViewService _svcs;

		public RelayCommand<CommandParameter> SelectContactCommand { get { return new RelayCommand<CommandParameter>(SelectContact); } }
		void SelectContact(CommandParameter param) {
			param.ToString();
		}

		public RelayCommand<IViewService> RefreshCommand { get { return new RelayCommand<IViewService>(svcs => LoadAsync(svcs)); } }
	}
}